<template>
  <div class="app-main">
    <div class="search-box">
      <el-form :inline="true" size="mini" :model="listParams" ref="searchForm">
        <search-form-box :show-more-btn="true">
          <template slot="showSearch">
            <el-form-item label="客户名称：" prop="customer_id">
              <el-select filterable clearable v-model="listParams.customer_id" placeholder="请选择项目" style="width: 100%">
                <el-option v-for="(item,index) in customerArr" :value="item.id" :label="item.name" :key="item.id" />
              </el-select>
            </el-form-item>
			<el-form-item label="供应商：" prop="supplier_ids_arr">
			  <el-select filterable clearable multiple v-model="listParams.supplier_ids_arr" placeholder="请选择供应商" style="width: 100%">
			    <el-option v-for="(item,index) in supplierArr" :value="item.id" :label="item.name" :key="item.id" />
			  </el-select>
			</el-form-item>
			<el-form-item label="提交日期：" prop="created_at_start">
			  <el-date-picker v-model="listParams.created_at_start" type="date" placeholder="选择日期"
			    value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
			  </el-date-picker>
			</el-form-item>
			<el-form-item label="至" prop="created_at_end">
			  <el-date-picker v-model="listParams.created_at_end" type="date" placeholder="选择日期"
			    value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
			  </el-date-picker>
			</el-form-item>
          </template>
          <template slot="hideSearch">
			  <el-form-item label="合同编号：" prop="contract_num">
			    <el-input v-model="listParams.contract_num" placeholder="请输入合同编号" clearable></el-input>
			  </el-form-item>
            <el-form-item label="公司：" prop="dept_id">
              <el-select filterable clearable v-model="listParams.dept_id" placeholder="请选择公司" style="width: 100%">
                <el-option v-for="(item,index) in companyArr" :value="item.id" :label="item.name" :key="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="最晚上刊日期：" prop="latest_up_date_start">
              <el-date-picker v-model="listParams.latest_up_date_start" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="至" prop="latest_up_date_end">
              <el-date-picker v-model="listParams.latest_up_date_end" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="最晚下刊日期：" prop="latest_down_date_start">
              <el-date-picker v-model="listParams.latest_down_date_start" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="至" prop="latest_down_date_end">
              <el-date-picker v-model="listParams.latest_down_date_end" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px">
              </el-date-picker>
            </el-form-item>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button type="primary" @click="searchForm('searchForm')">查询</el-button>
              <el-button @click="resetForm('searchForm')">重置</el-button>
			  <el-button @click="exportExcel">导出</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>


    <div class="table-box">
      <el-button v-permission="'create_ad_make_order'" type="primary" size="mini" style="margin-bottom: 10px"
        @click="toCreate">新建制作单
      </el-button>
      <!-- <el-button v-permission="'create_ad_make_order'" type="primary" size="mini" style="margin-bottom: 10px"
        @click="toConfirm">供应商确认单
      </el-button> -->
      <!-- <el-button v-permission="'create_ad_make_order'" type="primary" size="mini" style="margin-bottom: 10px"
        @click="toDetailDialog">详情弹框
      </el-button> -->


      <el-table :data="tableData" size="mini" border style="width: 100%" v-loading="tableLoading" :max-height="tableMaxHeight">
        <el-table-column type="index" label="序号" width="50" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
		<el-table-column label="画面" min-width="200" align="center">
		  <template slot-scope="scope">
		    <div class="flex align-center justify-center flex-wrap">
		      <div class="text-center" v-for="(item,index) in scope.row.picList" :key="index">
		        <el-image style="width: 60px; height:auto;margin: 5px;" :src="item" fit="contain"
		          :preview-src-list="scope.row.picList">
		        </el-image>
		      </div>
		    </div>
		  </template>
		</el-table-column>
		<el-table-column label="提交日期" width="100" align="center">
			<template slot-scope="scope">
				{{ scope.row.created_at ? scope.row.created_at.substring(0, 10) : '' }}
			</template>
		</el-table-column>
		<el-table-column prop="dept_name" label="公司" width="80" align="center"></el-table-column>
    <el-table-column prop="customer_name" label="客户名称" width="180" align="center"></el-table-column>
		<el-table-column label="资源" width="150" align="center">
		  <template slot-scope="scope">
			  <div class="flex justify-center align-center flex-direction">
				  <el-tag size="mini" v-for="item in scope.row.mediaCountList">
				    {{ item.name }}: {{item.num}}个
				  </el-tag>
			  </div>
		  </template>
		</el-table-column>
		<el-table-column label="供应商" min-width="400" align="center" show-overflow-tooltip>
		  <template slot-scope="scope">
			  <div class="flex justify-center align-center flex-direction">
				  <el-descriptions border title="" :colon="false" size="mini" v-for="item in scope.row.supplierPicCountList">
				      <el-descriptions-item label="供应商" :span="2">{{item.supplier}}</el-descriptions-item>
					  <el-descriptions-item label="总价(元)">{{item.total}}</el-descriptions-item>
					  <el-descriptions-item label="材质">{{item.pic_type}}</el-descriptions-item>
				      <el-descriptions-item label="宽(m)">{{item.size_width}}</el-descriptions-item>
				      <el-descriptions-item label="高(m)">{{item.size_height}}</el-descriptions-item>
				      <el-descriptions-item label="总面积(m²)">{{item.size_area}}</el-descriptions-item>
				      <el-descriptions-item label="数量(幅)">{{item.num}}</el-descriptions-item>
				      <el-descriptions-item label="单价(元)">{{item.price}}</el-descriptions-item>
				  </el-descriptions>
			  </div>
		  </template>
		</el-table-column>
		<el-table-column prop="contract_num" label="合同编号" width="140" align="center"></el-table-column>
		<el-table-column label="时间段" width="180" align="center">
		  <template slot-scope="scope">
		    <el-tag size="mini" v-if="scope.row.type==='OUT'" type="info">
		      {{ scope.row.daterange_start + '~' + scope.row.daterange_end }}
		    </el-tag>
		  </template>
		</el-table-column>
        <el-table-column label="类型" width="80" align="center">
          <template slot-scope="scope">
            {{ scope.row.type === 'IN' ? '内单' : '外单' }}
          </template>
        </el-table-column>
        <el-table-column prop="flow_applyer" label="申请人" width="80" align="center"></el-table-column>
        <el-table-column prop="memo" label="备注" min-width="100" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="审核状态" fixed="right" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.flow_status === 3" size="mini" type="primary">流程中</el-tag>
            <el-tag v-if="scope.row.flow_status === 4" size="mini" type="success">已通过</el-tag>
            <el-tag v-if="scope.row.flow_status === 2" size="mini" type="danger">被退回</el-tag>
            <el-tag v-if="scope.row.flow_status === 0" size="mini" type="info">草稿箱</el-tag>
          </template>
        </el-table-column>
		<el-table-column label="生成状态" fixed="right" width="90" align="center">
		  <template slot-scope="scope">
		    <el-tag size="mini" v-if="scope.row.gen_status===1">未生成</el-tag>
		    <el-tag type="warning" size="mini" v-if="scope.row.gen_status===2">部分生成</el-tag>
		    <el-tag type="success" size="mini" v-if="scope.row.gen_status===3">全部生成</el-tag>
		  </template>
		</el-table-column>
		<el-table-column label="确认状态" fixed="right" width="90" align="center">
		  <template slot-scope="scope">
		    <el-tag size="mini" v-if="scope.row.confirm_status===1">未确认</el-tag>
		    <el-tag type="warning" size="mini" v-if="scope.row.confirm_status===2">部分确认</el-tag>
		    <el-tag type="success" size="mini" v-if="scope.row.confirm_status===3">全部确认</el-tag>
		  </template>
		</el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template slot-scope="{row,$index}">
			  <el-button-group>
				  <el-button type="primary" size="mini" @click="toDetail(row.id)">
				    查看
				  </el-button>
				  <el-button type="primary" icon="el-icon-link" size="mini" v-if="row.flow_status === 4 && row.gen_status===1"
				    @click="showSupplier(row.id)">
				    生成链接
				  </el-button>
				  <el-button type="success" icon="el-icon-link" size="mini" v-if="row.flow_status === 4 && row.gen_status>1"
				    @click="showSupplier(row.id)">
				    查看链接
				  </el-button>
			  </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination :current-page="listParams.page" :page-sizes="[10,20,50,100, 200,400]"
      layout="total, sizes, prev, pager, next, jumper" :page-size="listParams.page_size" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>


    <!-- 生成链接 -->
    <el-dialog :title="cuForm.status?'查看链接':'生成链接'" :visible.sync="dialogVisible" width="60%" center>
      <el-form :model="cuForm" ref="cuForm" v-loading="dialogLoading" size="mini">
        <div class="margin-bottom-sm" style="font-size: 16px;">
          <div class="margin-bottom-sm">合同编号：{{ cuForm.contract_num || '' }}</div>
          <div class="margin-bottom-xs">项目：{{ cuForm.customer_name || '' }}</div>
          <div class="margin-bottom-xs">时间段：<el-tag size="small" style="font-size: 16px;" v-if="cuForm.type==='OUT'">
              {{ cuForm.daterange_start + '~' + cuForm.daterange_start }}
            </el-tag>
          </div>
        </div>

        <el-table :data="tableDataSupplier" size="mini" border style="width: 100%">
          <el-table-column type="index" label="序号" width="50" align="center">
            <template slot-scope="scope">
              <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="supplier" label="供应商" width="200" align="center" />
          <el-table-column label="画面" width="300" align="center">
            <template slot-scope="{row,$index}">
              <div class="flex align-center justify-center flex-wrap">
                <div class="text-center" style="width: 24%;" v-for="(item,index) in row.pics" :key="index">
                  <el-image style="width: 60px; height:auto;margin: 5px;" :src="item" fit="contain"
                    :preview-src-list="row.pics">
                  </el-image>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量" width="100" align="center" />
          <el-table-column prop="run" label="跑腿平台" width="100" align="center" />
          <el-table-column prop="run_cost" label="跑腿费" width="100" align="center" />
          <el-table-column prop="deliver_time" label="送达时间" width="200" align="center" />
          <el-table-column fixed="right" label="生成状态" width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-tag size="mini" v-if="row.gen_confirm_status===1">未生成</el-tag>
              <el-tag type="warning" size="mini" v-if="row.gen_confirm_status===2">待确认</el-tag>
              <el-tag type="success" size="mini" v-if="row.gen_confirm_status===3">已确认</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template slot-scope="{row,$index}">
              <el-button type="primary" icon="el-icon-link" size="mini" v-if="row.gen_confirm_status===1"
                @click="createLink(row, $index)">
                生成链接
              </el-button>
              <el-button type="success" icon="el-icon-link" size="mini" v-if="row.gen_confirm_status>1"
                @click="copyLink(row, $index)">
                复制链接
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>


      <span slot="footer" class="dialog-footer ">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <AdMakeOrderDialog ref="AdMarketOrderDialog" :adMarketOrderId="adMarketOrderId" />

  </div>
</template>

<script>
  import { get_company } from '@/api/system/department'
  import { company_list_all } from '@/api/customer/customer'
  import { no_page_list } from '@/api/supplier/supplier'
  import { list, confirm_list, generate_confirm_link, get_confirm_link, exportSupplierDataExcel } from '@/api/business/ad_make_order'
  import SearchFormBox from '@/components/SearchFormBox'
  import AdMakeOrderDialog from './components/AdMakeOrderDialog'
  import common from '@/utils/common.js'
  import {
    generateUUID
  } from '@/utils/util'
  import {
    outputDir
  } from '@/settings'

  export default {
    name: 'ADMakeOrder',
    components: {
      SearchFormBox,
      AdMakeOrderDialog
    },
    data() {
      return {
        tableMaxHeight: 0,
        listParams: {
          page: 1,
          page_size: 10,
          dept_id: null,
          customer_id: null,
          contract_num: null,
          flow_status: null,
          latest_up_date_start: null,
          latest_up_date_end: null,
          latest_down_date_start: null,
          latest_down_date_end: null,
          created_at_start: null,
          created_at_end: null,
		  supplier_ids_arr: []
        },
        total: 0,
        tableData: [],
        tableLoading: false,
        companyArr: [],
        customerArr: [],
		supplierArr: [],
        // 弹出框
        dialogLoading: false,
        dialogVisible: false,
        cuForm: {},
        tableDataSupplier: [],
        adMarketOrderId: null

      }
    },
    created() {
      this.tableMaxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
      this.getCustomerList()
      this.getCompanyList()
	    this.getSupplierList()
      this.getList()
    },
    methods: {
		getSupplierList(materialId) { // 根据materialId获取供应商列表
		  no_page_list({}).then(res => {
		    this.supplierArr = res.data.map(item => {
				return {
				id: item.id,
				name: item.name
				}
			})
		  })
		},
		exportExcel(){
			exportSupplierDataExcel(this.listParams);
		},
      getCompanyList() { // 获取公司列表
        get_company().then(res => {
          this.companyArr = res.data.map(item => {
            return {
              id: item.id,
              name: item.head
            }
          })
        })
      },
      getCustomerList() { // 获取项目列表
        company_list_all().then(res => {
          this.customerArr = res.data.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          })
        })
      },
      getList() {
        this.tableLoading = true
		if((this.listParams.supplier_ids_arr || []).length > 0) this.listParams.supplier_ids_str = this.listParams.supplier_ids_arr.join(',');
		else this.listParams.supplier_ids_str = null;
        list(this.listParams).then(res => {
          this.tableLoading = false
          this.tableData = res.data.records
          this.total = res.data.total
        }).catch(res => {
          this.tableLoading = false
        })
      },
			searchForm(formName){
				this.listParams.page = 1
				this.getList()
			},
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.getList()
      },
      handleSizeChange(val) {
        this.listParams.page_size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listParams.page = val
        this.getList()
      },
      toCreate() { // 跳转新建制作单
        const uuid = generateUUID()
        this.$store.commit('keep/PUT_PAGE_PARAMS', {
          uuid: uuid,
          data: {
            is_create: true
          }
        })
        this.$router.push({
          name: 'create_ad_make_order_detail',
          query: {
            uuid
          }
        })
      },
      toDetail(id) { // 跳转制作单详情
        let uuid = generateUUID()
        this.$store.commit('keep/PUT_PAGE_PARAMS', {
          uuid: uuid,
          data: {
            id: id
          }
        })
        this.$router.push({
          name: 'look_ad_make_order_detail',
          query: {
            uuid
          }
        })
      },
      showSupplier(id) { // 显示生成链接弹出框
        this.dialogVisible = true
        this.dialogLoading = true
        confirm_list({
          ad_make_id: id
        }).then(res => {
          let {
            data
          } = res
          const confirmVOList = data.confirmVOList
          var list = []
          for (var i in confirmVOList) {
            var o = confirmVOList[i],
              deliver_normal = o.deliver_normal
            if (deliver_normal.length) {
              var arr = deliver_normal[0]
              o.run = arr.run
              o.run_cost = arr.run_cost
            }
            list.push(o)
          }
          this.cuForm = data
          this.tableDataSupplier = list
          this.dialogLoading = false
        }).catch(res => {
          this.dialogLoading = false
        })
      },
      createLink(row, index) { // 生成链接
        const that = this
        common.confirmDialog('您确定要生成链接?').then(() => {
          this.dialogLoading = true
          generate_confirm_link({
            bill_ad_make_id: row.bill_ad_make_id,
            supplier_id: row.supplier_id
          }).then(res => {
            this.$message.success('生成成功，稍等将弹出链接')
            setTimeout(() => {
              that.tableDataSupplier[index].gen_confirm_status = 2
              that.dialogLoading = false
              const url = outputDir === 'local' ? 'http://localhost:9528' : 'https://oa.meilaiwenhua.com',
                text = url + '/#/supplier_check?batchStr=' + res.message
              that.$alert(text, '链接', {
                confirmButtonText: '复制',
                callback: () => {
                  that.doCopy(text)
                }
              })
            }, 1000)
          }).catch(res => {
            this.dialogLoading = false
          })
        })
      },
      copyLink(row, index) { // 复制链接
        const that = this
        this.dialogLoading = true
        get_confirm_link({
          bill_ad_make_id: row.bill_ad_make_id,
          supplier_id: row.supplier_id
        }).then(res => {
          that.dialogLoading = false
          const url = outputDir === 'local' ? 'http://localhost:9528' : 'https://oa.meilaiwenhua.com',
            text = url + '/#/supplier_check?batchStr=' + res.message
          that.$alert(text, '链接', {
            confirmButtonText: '复制',
            callback: () => {
              that.doCopy(text)
            }
          })
        }).catch(res => {
          this.dialogLoading = false
        })
      },
      doCopy(text) {
        this.$copyText(text).then((res) => {
          console.log('内容已复制到剪切板！，复制的内容为：' + res.text)
        }).catch(err => {
          this.$message.error('复制失败')
        })
      },
      toConfirm() { // 跳转供应商确认单
        window.open('/#/supplier_check?batchStr=a75a92b0880246e59b5ae259d8941368')
      },
      toDetailDialog() {
        let arr = [31, 44]
        this.adMarketOrderId = arr[(Math.random() > 0.5) ? 1 : 0];
        this.$refs.AdMarketOrderDialog.open();
      }

    }
  }
</script>

<style scoped>
  .app-main {
    padding: 0 20px;
  }

  .search-box {
    margin-top: 10px;
  }

  .table-box {
    margin-bottom: 20px;
  }

  /deep/ .choosed-data {
    background-color: #e9f9ff !important;
  }
</style>
